package com.cci.kangdao.externalData.controller;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.ExternalAuthMapper;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.ExternalAuthInfo;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.dto.RoadTestHeader;
import com.cci.kangdao.externalData.dto.request.ExternalDataESNRequest;
import com.cci.kangdao.externalData.dto.request.ExternalDataUserRequest;
import com.cci.kangdao.externalData.dto.request.LyhFileUserRequest;
import com.cci.kangdao.externalData.dto.response.ExternalUserResponse;
import com.cci.kangdao.externalData.model.SynchroESNInfo;
import com.cci.kangdao.externalData.model.SynchroUserInfo;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.service.impl.SMSEnum;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.gexin.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 外部数据同步
 *
 * @author sw
 */
@RestController
@RequestMapping("/externalDataSynchro")
@Slf4j
public class ExternalDataSynchroController {

    @Resource
    private ExternalDataSynchroService externalDataSynchroService;
    @Resource
    private ExternalAuthMapper externalAuthMapper;
    @Resource
    private UserTDao userTDao;

    /**
     * 同步用户 作废
     *
     * @return
     */
    @RequestMapping(value = "/synchroUser.aspx", method = RequestMethod.POST)
    public BaseResponse synchroUser(@RequestBody ExternalDataUserRequest userRequest,@RequestHeader Map<String, String> headerMap) {
        try {
            //验证token
            RoadTestHeader header = JSON.parseObject(JSON.toJSONString(headerMap), RoadTestHeader.class);
            log.info("入参:" + userRequest);
            log.info("header信息:" + header);
            if(null == header){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            if(StringUtils.isBlank(header.getSource()) || StringUtils.isBlank(header.getToken()) || StringUtils.isBlank(header.getSystemTime())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            ExternalAuthInfo authInfo = externalAuthMapper.getAuthBySource(header.getSource(),"1");
            if(null == authInfo){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "未查询到token信息");
            }
            if(!authInfo.getToken().equals(header.getToken())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "token验证失败");
            }
            if(CollectionUtils.isEmpty(userRequest.getUserList())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "参数不能为空");
            }
            for(SynchroUserInfo userInfo : userRequest.getUserList()){
                if(StringUtils.isBlank(userInfo.getPhone())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "手机号不能为空");
                }
                if(StringUtils.isBlank(userInfo.getUserId())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "用户标识不能为空");
                }
                if(StringUtils.isBlank(userInfo.getContact())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "姓名不能为空");
                }
            }

            return externalDataSynchroService.synchroUser(userRequest,header.getSource());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return BaseResponse.error("未知错误");
        }
    }

    /**
     * 验证手机号 作废
     *
     * @return
     */
    @RequestMapping(value = "/verifyPhone.aspx", method = RequestMethod.POST)
    public BaseResponse verifyPhone(@RequestBody SynchroUserInfo userRequest,@RequestHeader Map<String, String> headerMap) {
        try {
            //验证token
            RoadTestHeader header = JSON.parseObject(JSON.toJSONString(headerMap), RoadTestHeader.class);
            log.info("入参:" + userRequest);
            log.info("header信息:" + header);
            if(null == header){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            if(StringUtils.isBlank(header.getSource()) || StringUtils.isBlank(header.getToken()) || StringUtils.isBlank(header.getSystemTime())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            ExternalAuthInfo authInfo = externalAuthMapper.getAuthBySource(header.getSource(),"1");
            if(null == authInfo){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "未查询到token信息");
            }
            if(!authInfo.getToken().equals(header.getToken())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "token验证失败");
            }
            if(StringUtils.isBlank(userRequest.getPhone())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "手机号不能为空");
            }
            UserT userT = userTDao.getUserByPhone(userRequest.getPhone());
            int i = 0;
            if (null != userT) {
                //是否为终端用户
                i = userTDao.isEndUser(userT.getId());
            }
            ExternalUserResponse response = new ExternalUserResponse();
            response.setPhone(userRequest.getPhone());
            response.setUserType(null != userT ? 1 : 0);
            response.setEndUserType(i > 0 ? 1 : 0);
            return BaseResponse.success(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return BaseResponse.error("未知错误");
        }
    }

    /**
     * 同步esn 作废
     *
     * @return
     */
    @RequestMapping(value = "/synchroEsn.aspx", method = RequestMethod.POST)
    public BaseResponse synchroEsn(@RequestBody ExternalDataESNRequest esnRequest, @RequestHeader Map<String, String> headerMap) {
        try {
            //验证token
            RoadTestHeader header = JSON.parseObject(JSON.toJSONString(headerMap), RoadTestHeader.class);
            log.info("入参:" + esnRequest);
            log.info("header信息:" + header);
            if(null == header){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            if(StringUtils.isBlank(header.getSource()) || StringUtils.isBlank(header.getToken()) || StringUtils.isBlank(header.getSystemTime())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "缺少token参数");
            }
            ExternalAuthInfo authInfo = externalAuthMapper.getAuthBySource(header.getSource(),"1");
            if(null == authInfo){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "未查询到token信息");
            }
            if(!authInfo.getToken().equals(header.getToken())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "token验证失败");
            }
            if(CollectionUtils.isEmpty(esnRequest.getEsnList())){
                return BaseResponse.error(SMSEnum.type17.getIndex(), "参数不能为空");
            }
            for(SynchroESNInfo esnInfo : esnRequest.getEsnList()){
                if(StringUtils.isBlank(esnInfo.getPhone())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "手机号不能为空");
                }
                if(StringUtils.isBlank(esnInfo.getEsn())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "esn不能为空");
                }
                if(!StringUtils.isNumeric(esnInfo.getEsn()) || esnInfo.getEsn().length() > 8){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "esn格式不正确");
                }
                if(StringUtils.isBlank(esnInfo.getPlateNumber())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "车牌号不能为空");
                }
                if(StringUtils.isBlank(esnInfo.getOperation())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "操作标识不能为空");
                }
                if(StringUtils.isBlank(esnInfo.getExternalUserId())){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "用户标识不能为空");
                }
                if(null == esnInfo.getEAppUserId()){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "用户id不能为空");
                }
                if(!esnInfo.getOperation().equals("ADD")
                        && !esnInfo.getOperation().equals("UPDATE")
                        && !esnInfo.getOperation().equals("DEL")){
                    return BaseResponse.error(SMSEnum.type17.getIndex(), "操作标识错误");
                }
            }

            return BaseResponse.success();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return BaseResponse.error("未知错误");
        }
    }


    /**
     * 注册时接收老友会用户
     * @return
     */
    @RequestMapping(value = "/receiveLyhUser.aspx", method = RequestMethod.POST)
    public BaseResponse receiveLyhUser(@RequestBody LyhFileUserRequest userRequest) {
        externalDataSynchroService.receiveLyhUser(userRequest);
        return BaseResponse.success();
    }

    /**
     * 手动接收老友会车辆
     * @return
     */
    @RequestMapping(value = "/receiveLyhVehicle.aspx", method = RequestMethod.GET)
    public BaseResponse receiveLyhVehicle() {
        UserT userT = UserThreadLocal.get();
        LyhFileUserRequest userRequest = new LyhFileUserRequest();
        userRequest.setUserId(userT.getId());
        externalDataSynchroService.receiveLyhVehicle(userRequest);
        return BaseResponse.success();
    }

    /**
     * 推送老友会用户
     * @return
     */
    @RequestMapping(value = "/pushLyhUser.aspx", method = RequestMethod.POST)
    public BaseResponse pushLyhUser(@RequestBody LyhFileUserRequest userRequest) {
        externalDataSynchroService.pushLyhUser(userRequest);
        return BaseResponse.success();
    }

    /**
     * 推送老友会esn
     * @return
     */
    @RequestMapping(value = "/pushLyhEsn.aspx", method = RequestMethod.POST)
    public BaseResponse pushLyhEsn(@RequestBody SynchroESNInfo request) {
        externalDataSynchroService.pushLyhEsn(request.getUserId(),request.getEsn(),request.getPlateNumber(),request.getOperation());
        return BaseResponse.success();
    }

    /**
     * 文件方式
     * @return
     */
    @RequestMapping(value = "/pushLyhEsnList.aspx", method = RequestMethod.POST)
    public BaseResponse pushLyhEsnList(@RequestBody SynchroESNInfo request) {
        externalDataSynchroService.pushLyhEsnList(request.getEAppUserId(),request.getOperation());
        return BaseResponse.success();
    }


    /**
     * 定时调用接收老友会用户
     *
     * @return
     */
    @RequestMapping(value = "/timingReceiveLyhUser.aspx", method = RequestMethod.POST)
    public BaseResponse timingReceiveLyhUser(@RequestBody ExternalDataUserRequest userRequest) {
        try {
            log.info("入参:" + userRequest);
            return externalDataSynchroService.synchroUser(userRequest,"laoyouhui");
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return BaseResponse.error("未知错误");
        }
    }

    /**
     * 删除用户车辆车队信息
     *
     * @return
     */
    @RequestMapping(value = "/deleteEsnAndFleet.aspx", method = RequestMethod.POST)
    public BaseResponse deleteEsnAndFleet(@RequestBody ExternalDataUserRequest userRequest) {
        try {
            log.info("入参:" + userRequest);
            if(CollectionUtils.isNotEmpty(userRequest.getUserIdList())){
                for(Long userId : userRequest.getUserIdList()){
                    externalDataSynchroService.deleteEsnAndFleet(userId);
                }
            }
            return BaseResponse.success();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return BaseResponse.error("未知错误");
        }
    }
}
